const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 复制文本
const copyText = text =>{
  wx.setClipboardData({
    data: text,
    success:function(res){
      wx.getClipboardData({
        success: (option) => {
          wx.showToast({
            title: '复制成功',
            icon: 'succe',
            duration: 2000
          })
        },
      })
    }
  })
}

//弹出框
const success = (fallback) => {
  wx.showToast({
    title: "操作成功",
    icon: "success",
    duration: 2000,
    success: function(){
      if(fallback != null){
        setTimeout(fallback, 2000);
      }
    }
  });
}

const error = (fallback) => {
  wx.showToast({
    title: "操作失败",
    icon: "success",
    duration: 2000,
    success: function(){
      if(fallback != null){
        setTimeout(fallback, 2000);
      }
    }
  });
}

const warning = (title) => {
  wx.showToast({
    title: title,
    icon: "none",
    duration: 1500,
    success: function(){
    }
  });
}


/**
 * 上传图片到OSS 服务器
 * @param {*} fileList  上传图片路径
 * @param {*} callback  上传完成后的回调方法
 * 1.首选获取图片签名信息
 * 2.上传图片
 */

const uploadFileToOss = (prefix, fileList, callback)=>{
  const userId = wx.getStorageSync('userInfo').id;
  wx.showLoading({title: '正在上传图片', mask: true});
  wx.request({
    url: `${BASE_URL}oss/getSign?userId=${userId}&prefix=${prefix}`,
    method: 'GET',
    success: function(res){
      let { policy, accessid, signature, host, dir } = res.data;
      let pathList = [], total = 0;
      let timestamp = new Date().getTime();
      for(let i = 0,len = fileList.length; i < len; i++){
        let filePath = fileList[i];
        let fileName = filePath.lastIndexOf('.') // 取到文件名开始到最后一个点的长度
        let fileNameLength = filePath.length // 取到文件名长度
        let fileFormat = filePath.substring(fileName + 1, fileNameLength) // 截
        const imgPath = `${dir}${timestamp}_${i}.${fileFormat}`;
        wx.uploadFile({
          filePath: fileList[i],
          name: 'name',
          url: host,
          name: 'file',
          formData: {
            key: imgPath,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
          },
          success: function(res){
            if (res.statusCode === 200) {
              // 我这个地方是图片，需要上传成功后展示，所以就再一次进行了拼接并展示
              pathList.push(`${host}/${imgPath}`);
              total += 1;
              console.log('上传了', total);
              if(total >= len){
                wx.hideLoading({
                  success: (res) => {},
                });
                callback(pathList);
              }
            } else {
              wx.hideLoading({
                success: (res) => {},
              });
              error('上传失败')
            }
          }
        })
      }
    },
    fail: function(err){
      wx.hideLoading({
        success: (res) => {},
      });
      error();
    }
  })
}

// 验证是否登录
const verifyHasLogin = () =>{
  const applicant = wx.getStorageSync('userInfo').id;
  if(applicant){
    return applicant;
  }else{
    wx.showModal({
      content: '此操作需要登录',
      cancelColor: '#333333',
      confirmColor: '#477FF7',
      success: function(res){
        if(res.confirm){
          wx.navigateTo({
            url: '/pages/login/login',
          })
        }
      }
    });
    return false;
  }
}

// 服务器 IP 地址与请求端口
// var IP = "http://192.168.1.4:8080/pick";
var IP = "https://www.yby.ink/pick";
var BASE_URL = "" + IP + "/";

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}





module.exports = {
  formatTime: formatTime,
  copyText:copyText,
  BASE_URL:BASE_URL,
  success: success,
  error: error,
  warning,
  uploadFileToOss,
  verifyHasLogin
}
